<template>
  <div class="house-search-page">
    <!-- 搜索区域 -->
    <el-card class="search-card mb-3">
      <template #header>
        <div class="card-header">
          <i class="el-icon-search mr-2"></i>房源搜索
        </div>
      </template>
      <div class="search-bar">
        <el-input
            v-model="searchQuery"
            placeholder="请输入区域名称..."
            prefix-icon="el-icon-search"
            class="search-input"
            clearable
        >
          <el-button slot="append" type="primary" @click="fetchHouseList">
            <i class="el-icon-search mr-1"></i>搜索
          </el-button>
        </el-input>

        <el-button type="success" @click="exportData" size="small">
          <i class="el-icon-download mr-1"></i>导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="house-table-card">
      <template #header>
        <div class="card-header">
          <i class="el-icon-s-grid mr-2"></i>房源列表
          <span class="ml-2 text-muted">共 {{ total }} 条数据</span>
        </div>
      </template>

      <div class="table-container">
        <el-table
            :data="houseList"
            border
            stripe
            highlight-current-row
            size="small"
            empty-text="暂无数据"
            @row-click="viewDetails"
            v-loading="loading"
        >
          <el-table-column prop="plotId" label="小区ID" width="120" align="center"></el-table-column>
          <el-table-column prop="plotName" label="小区名称" width="120"></el-table-column>
          <el-table-column prop="property" label="属性" width="300">
            <template slot-scope="scope">
              <div class="attribute-tags">
                <span
                    v-for="(attr, index) in (scope.row.property || '').split(' | ')"
                    :key="index"
                    class="tag"
                >
                  {{ attr }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="houseId" label="房源ID" width="150" align="center"></el-table-column>
          <el-table-column prop="totalAmount" label="总金额" width="80" align="right">
            <template slot-scope="scope">
              <span class="text-danger font-weight-bold">{{ scope.row.totalAmount || '0' }}</span> 千元
            </template>
          </el-table-column>
          <el-table-column prop="date01" label="日期" width="160" align="center"></el-table-column>
          <el-table-column prop="quYu" label="区域" width="100"></el-table-column>
          <el-table-column prop="city" label="城市" width="90"></el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  @click.stop="viewDetails(scope.row)"
              >
                <i class="el-icon-view mr-1"></i>详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 房源详情弹窗 -->
    <el-dialog
        title="房源详情"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose"
    >
      <div class="detail-content">
        <el-row :gutter="20">
          <el-col :span="12"><strong>小区名称：</strong>{{ currentHouse.plotName }}</el-col>
          <el-col :span="12"><strong>小区ID：</strong>{{ currentHouse.plotId }}</el-col>
        </el-row>
        <el-row :gutter="20" class="mt-2">
          <el-col :span="12"><strong>房源ID：</strong>{{ currentHouse.houseId }}</el-col>
          <el-col :span="12"><strong>总金额：</strong><span class="text-danger">{{ currentHouse.totalAmount || '0' }}</span> 千元</el-col>
        </el-row>
        <el-row :gutter="20" class="mt-2">
          <el-col :span="12"><strong>区域：</strong>{{ currentHouse.quYu }}</el-col>
          <el-col :span="12"><strong>城市：</strong>{{ currentHouse.city }}</el-col>
        </el-row>
        <el-row :gutter="20" class="mt-2">
          <el-col :span="24"><strong>属性：</strong>
            <div class="attribute-tags">
          <span v-for="(attr, index) in (currentHouse.property || '').split(' | ')" :key="index" class="tag">
            {{ attr }}
          </span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mt-2">
          <el-col :span="12"><strong>日期：</strong>{{ currentHouse.date01 }}</el-col>
        </el-row>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

  </div>

</template>

<script>
import * as XLSX from 'xlsx';

export default {
  name: 'HouseSearch',
  data() {
    return {
      searchQuery: '',
      houseList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      dialogVisible: false, // 控制弹窗显示
      currentHouse: {} // 当前选中的房源对象
    }
  }
,
  created() {
    this.fetchHouseList()
  },
  methods: {
    async fetchHouseList() {
      this.loading = true;
      try {
        const response = await this.$request.get('/selectAllHouse', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            quyu: this.searchQuery
          }
        });
        // 检查响应结构是否符合预期，修改判断字段为rows
        if (response && response.data && Array.isArray(response.data.rows)) {
          this.houseList = response.data.rows.map(house => ({
            ...house,
            plotId: house.plotId || '无',
            plotName: house.plotName || '无名称',
            totalAmount: house.totalAmount || '0',
            quYu: house.quYu || '未知区域',
          }));

          // 从后端获取总数据量
          this.total = response.data.total;
        } else {
          console.error('返回的数据格式错误:', response);
          this.houseList = [];
          this.total = 0;
        }
      } catch (error) {
        console.error('获取房源数据失败:', error);
        this.$message.error('获取房源数据失败');
      } finally {
        this.loading = false;
      }
    },

    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchHouseList()
    },

    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchHouseList()
    },

    viewDetails(row) {
      this.currentHouse = row;
      this.dialogVisible = true;
    },



    exportData() {
      this.$confirm('确定要导出当前数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const data = this.houseList;

        if (!data || data.length === 0) {
          this.$message.warning('没有可导出的数据');
          return;
        }

        // 转换数据结构为适合导出的对象数组
        const exportData = data.map(row => ({
          小区名称: row.plotName,
          小区ID: row.plotId,
          房源ID: row.houseId,
          总金额千元: row.totalAmount,
          区域: row.quYu,
          城市: row.city,
          日期: row.date01
        }));

        // 使用 SheetJS 创建工作表
        const ws = XLSX.utils.json_to_sheet(exportData);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '房源数据');

        // 导出文件
        XLSX.writeFile(wb, '房源数据.xlsx');

        this.$message.success('Excel 文件导出成功');
      }).catch(() => {
        // 用户取消操作
      });
    }

  }
}
</script>

<style scoped>
.house-search-page {
  height: 100%;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.house-table-card {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  min-height: calc(100vh - 220px);
}

.card-header {
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.search-input {
  flex: 1;
  max-width: 500px;
  margin-right: 15px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 10px;
}

.attribute-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.tag {
  background-color: #f0f2f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}

.text-danger {
  color: #f56c6c;
}

.font-weight-bold {
  font-weight: 600;
}

.text-muted {
  color: #909399;
}

.mb-3 {
  margin-bottom: 15px;
}
.detail-content .el-row {
  margin-bottom: 10px;
}

.detail-content .el-col {
  word-break: break-all;
}

.detail-content .text-danger {
  color: #f56c6c;
  font-weight: bold;
}

.detail-content .attribute-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.detail-content .tag {
  background-color: #f0f2f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}

</style>